package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    EmpService empService;



    /*
    //员工登录
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("员工登录：{}", emp);
        //根据用户名、密码查询员工对象
        Emp e = empService.login(emp);

        //判断e是否未空，如果不等于空，生成JWT令牌
        if (e != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", e.getId());
            map.put("username", e.getUsername());

            String jwt = Jwts.builder()
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 3600 * 24 * 7))
                    .signWith(SignatureAlgorithm.HS256, "itheima")
                    .setClaims(map) //体现出是哪个员工的信息
                    .compact();

            return Result.ok(jwt);
        } else {
            return Result.error("用户名或密码错误");
        }
    }
    */

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("员工登录:{}", emp);

        //根据用户名查询员工对象
        Emp e = empService.login2(emp.getUsername());

        //判断用户是否存在
        if (e == null) {
            return Result.error("用户名不存在");
        }

        //判断密码是否正确
        if (!e.getPassword().equals(emp.getPassword())) {
            return Result.error("密码错误");
        }

        //生成JWT令牌
        Map<String, Object> map = new HashMap<>();
        map.put("id", e.getId());
        map.put("username", e.getUsername());

        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7))
                .signWith(SignatureAlgorithm.HS256, "itheima")
                .compact();

        return Result.ok(jwt);

    }
}
